package il.ac.technion.wiki.api.expressions;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import il.ac.technion.wiki.api.search.Hit;
import il.ac.technion.wiki.api.search.IndexSearcher;

public class NotOp extends UnaryOperation{
	protected void evaluate(IndexSearcher iSearcher){
		element.evaluate(iSearcher);
		List<Hit> allDocs = iSearcher.getAllDocsHits();
		this.hits = zigzagJoin(element.hits, allDocs,iSearcher);
	}
	
	private List<Hit> zigzagJoin(List<Hit> hits1,List<Hit> allDocs,IndexSearcher iSearcher){
		List<Hit> $ = new LinkedList<Hit>();
		Collections.sort(hits1);
		Collections.sort(allDocs);
		Iterator<Hit> iter1= hits1.iterator();
		Iterator<Hit> iter2= allDocs.iterator();
		
		Hit h1 = null, h2 = null;
		if (iter1.hasNext()) h1 = iter1.next();
		if (iter2.hasNext()) h2 = iter2.next();
		
		while (h2 != null){
			if (h1 == null){
				$.add(new Hit(iSearcher.notScore(h2.getScore()), h2.getTitle()));
				h2 = null;
				if (iter2.hasNext()) 
					h2 = iter2.next();
				continue;
			}
			int res = h1.compareTo(h2);
			if (res == 0){
				h1=null; h2=null;
				if (iter1.hasNext()) 
					h1 = iter1.next();
				if (iter2.hasNext()) 
					h2 = iter2.next();
			}
			else if (res < 0){
				//TODO: add axception here
				System.out.println("shouldn't get here");
			}
			else if (res > 0){
				$.add(new Hit(1, h2.getTitle()));
				h2 = null;
				if (iter2.hasNext()) 
					h2 = iter2.next();
			}
		}
		return $;
	}
}
